import { from, Subject } from 'rxjs';
import { tap, filter, switchMap } from 'rxjs/operators'

import { readdir, stat, Stats } from 'fs'

async function fsReadDir(dir: string): Promise<string[]> {
  return new Promise<string[]>(
    (resolve, reject) => {
      readdir(dir, (err, files) => {
        if (err) reject(err);
        resolve(files);
      })
    }
  )
};

async function fsStat(currentPath: string) {
  return new Promise<Stats>(
    (resolve, reject) => {
      stat(currentPath, (err, stat) => {
        if (err) reject(err);
        resolve(stat);
      });
    }
  )
};

async function fsIsDirectory(currentPath: string): Promise<boolean> {
  let stat: Stats = await fsStat(currentPath);
  if (stat.isDirectory()) return true;
  return false;
}

// 视频流 单播，组播，广播，录播，回播，播放频率
const sub1 = new Subject();

// 截图
const sub2 = new Subject();

// 存储
const sub3 = new Subject();


async function test() {
  let dirFiles: string[] = [];
  console.log('目录列表:');
  from(fsReadDir('./')).pipe(
    tap({
      next: file => { console.log(`[tap1]${file}`); },
      error: error => { console.log(`[tap1] --- error --- ${error}`); },
      complete: () => { console.log(`[tap1] --- complete --- `); }
    }),
    switchMap(
      files => {
        return from(files).pipe(
          switchMap((file: string) => {
            return from(
              new Promise<string[]>(
                (resolve, reject) => {
                  stat(file, (err, stat) => {
                    if (err) reject(err);
                    if (stat.isDirectory()) {
                      console.log(`[Dir]${file}`);
                      dirFiles.push(file);
                      console.log(dirFiles);
                      resolve(dirFiles);
                    } else {
                      console.log(`[File]${file}`);
                      console.log(dirFiles);
                      resolve(dirFiles);
                    }
                  });
                }
              )
            )
          })
        )
      }
    ),
    tap(file => { console.log(`[tap2]${JSON.stringify(file)}`) })
  ).subscribe(file => { console.log(`${JSON.stringify(file)} `) });
}

test().then();